/**
 * 
 */
package com.manthano.applogin.authorization.handlers;

import java.io.IOException;
import java.util.Collection;
import java.util.Properties;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.WebAttributes;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import com.manthano.applogin.management.util.PropertyConfigUtil;

/**
 * @author Dell
 */
public class UserAuthenticationSuccessHandler implements AuthenticationSuccessHandler
{
	private RedirectStrategy	redirectStrategy	= new DefaultRedirectStrategy();

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
			Authentication authentication) throws IOException, ServletException
	{

		String targetUrl = determineTargetUrl(authentication);

		redirectStrategy.sendRedirect(request, response, targetUrl);
		clearAuthenticationAttributes(request);
	}

	protected void clearAuthenticationAttributes(HttpServletRequest request)
	{
		HttpSession session = request.getSession(false);
		if (session == null)
		{
			return;
		}
		session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
	}

	/**
	 * Builds the target URL according to the logic defined in the main class
	 * Javadoc.
	 * 
	 * @throws IOException
	 */
	protected String determineTargetUrl(Authentication authentication) throws IOException
	{
		Properties properties = PropertyConfigUtil.getLoginProperties();
		boolean isUser = false;
		boolean isAdmin = false;
		Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
		for (GrantedAuthority grantedAuthority : authorities)
		{
			if (grantedAuthority.getAuthority().equals("ROLE_USER"))
			{
				isUser = true;
				break;
			}
			else if (grantedAuthority.getAuthority().equals("ROLE_ADMIN"))
			{
				isAdmin = true;
				break;
			}
		}

		if (isUser)
		{
			return properties.getProperty("AUTHENTICATION_SUCCESS_URL");
		}
		else if (isAdmin)
		{
			return properties.getProperty("AUTHENTICATION_SUCCESS_URL");
		}
		else
		{
			throw new IllegalStateException();
		}
	}

	/**
	 * @param redirectStrategy
	 */
	public void setRedirectStrategy(RedirectStrategy redirectStrategy)
	{
		this.redirectStrategy = redirectStrategy;
	}

	protected RedirectStrategy getRedirectStrategy()
	{
		return redirectStrategy;
	}
}
